<template>
  <div class='tinymce'>
    <h1>
      <el-row>
        <el-col :span="5">
          <span v-if="dataArtice">修改推送</span>
          <span v-else>添加推送</span>
          <el-button class="addBtn" @click="goBack">返回</el-button>
        </el-col>
        <el-col :span="19" style="text-align:right">
           <el-button v-if="article" type="primary" @click="submitArticle('formAling')">修改文章</el-button>
           <el-button v-else type="success" @click="submitArticle('formAling')">保存</el-button>
        </el-col>
      </el-row>
    </h1>
    <div>
      
     <el-form  label-width="80px" :rules="aling" ref="formAling" :model="formLabelAlign">
        <el-form-item label="推送标题" prop="title">
          <el-input v-model="formLabelAlign.title"></el-input>
        </el-form-item>
        <el-form-item label="推送时间" prop="pushTime">
          <el-date-picker
            v-model="formLabelAlign.pushTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      
      <el-row>
        <div style="padding-left:20px;">
          <div class="initbox">
            <el-button class="initBtn" @click="upImageFun">图</el-button>
            <editor id='tinymce' v-model='tinymceHtml' :init='init'> </editor>
            
          </div>

          <el-button type="success" @click="submitArticle('formAling')">保存文章</el-button>
        </div>
      </el-row>
    
    </div>
    <el-dialog :visible.sync="imgstuts">
      <el-upload
        class="upload-demo"
        :action="action"
        :on-preview="handlePreview"
        :on-remove="handleRemoveEidt"
        :on-success="handleOkContent"
        ref="upload"
        :data="postData"
        multiple
       
        >
        <el-button size="small" type="primary">添加图片</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="backFun">取 消</el-button>
        <el-button type="primary" @click="apendHtml">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapActions,mapMutations,mapGetters,mapState} from 'vuex'
import Http from '@/Http/Http'
import qnUrl from '@/Http/qiniuUrl'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'

export default {
  name: 'tinymce',
  props:['dataArtice'],
  data () {
    const title = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入标题'))
      } else {
        callback()
      }
    }
    
    return {
      action:qnUrl,//七牛的上传地址
      postData:{
        token:'',
      },
      
      dialogImageUrl: '',
      dialogVisible: false,
       form1:{
        page_view:0,
        stars:0,
        hlpe:10001,
        line:1,
        value:0,
       
        
      },
      formLabelAlign:{
        title:'',
        pushTime:''
      },
      aling:{
        title:[
          {validator:title,trigger:'blur'}
        ]
      },

      imgstuts:false, //富文本编辑器部分
      tinymceHtml:'',
      fileList:[],
      init: {
        language_url: '/static/tinymce/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/static/tinymce/skins/lightgray',
        height: 300,
        plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
        toolbar:
          'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image | removeformat',
        branding: false
      }
    }
    
  },

  computed: {
    ...mapState(['article'])  
  },
  mounted () {
    
  },
  created() {
    this.getToken()
     const obj = document.getElementById('mceu_216')
  },
  methods:{
    getToken() {
      Http.QiniuToken({})
      .then( res => {
        this.postData.token = res.data.data.uptoken;
        this.tokenimgUrl = res.data.data.domain
      })
      .catch( error => {
        this.$router.push('/')
        
      })
    },
    handleRemove(file, fileList) {
      
    },
    handlePictureCardPreview(event, file, fileList) {
    },
    handleOkTitle(responed) {
    
      this.articleThum = `http://${this.tokenimgUrl}/${responed.key}`
   
    },
   
    submitArticle(val) {
      
      this.$refs[val].validate((valid) => {
       
        if (valid) {
          if (!this.articleThum) {
            this.$message.error('请上传文章封面图')
            return
          }
          // const reg = /function|script|alert|a()|iframe|onload/;

          // if (reg.test(this.tinymceHtml)){
          //   this.$message.error('不能出现敏感关键词')
          //   return
          // }
         
          const isRe = this.form1.type?1:0;
          const articleContent = this.tinymceHtml.replace(/50%/g,'100%');
          const param = {
            "articleTitle":this.formLabelAlign.title,  //文章标题
            "articleThum":this.articleThum,  //封面
            "articleStatus":this.form1.line,  //上线状态 
            "articleContent":articleContent, // 文章内容  实体列表 
            "articleUserid":this.form1.hlpe,
           
            "isRecommend":isRe, //推荐
            "topic":{
              "id":this.form1.value //分类 id 
            }
          }
          
          if (this.dataArtice) {
            param.articleId = this.dataArtice.articleId
            param.countLike = this.form1.stars;
            param.countRead = this.form1.page_view;
            this.postEditAriticeFun(param)
          } else {
            this.addAriticeFun(param)
          }
          
        } else {
          this.$message.error('请填写标题')
        }
      })
      
    },
    addAriticeFun(param) {
      Http.addAritice(param)
        .then( res => {
          if( res.data.code == 200 ){
            this.$message.success('文章发布成功')
            this.goBack()         
          } else if(res.data.code == -1003) {
            this.$message.error(`请求失败原因：${res.data.message}`)
            this.$router.push('/')
          }
        })
        .catch( error => {
          this.$message.error('服务器请求失败')
        })
    },
    postEditAriticeFun(param) {
      
      Http.postEditAritice(param)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('文章修改成功')
          this.goBack()         
        } else if(res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          this.$router.push('/')
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
      })
    },
    goBack(){
      this.$emit('getlist')
    },
    
    //富文本编辑器部分
    upImageFun(){
      this.imgstuts = true
    },
    handleRemoveEidt(file, fileList) {
      
    },
    handlePreview(file) {
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleOkContent(responed){
      this.fileList.push(`http://${this.tokenimgUrl}/${responed.key}`)
    },
    backFun(){
      this.imgstuts = false;
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    },
    apendHtml(){
      let arrHtml='';
      this.fileList.forEach(item => {
        arrHtml += `<img style="width:50%" src="${item}" alt=""/>`;
      })
      this.tinymceHtml = `${this.tinymceHtml}${arrHtml}`;
      this.imgstuts = false
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    }
  },
  components: {
    Editor,
  }
}
</script>
<style>
.el-textarea__inner{
  height:146px
}
.initbox{
  position: relative;
}
.initBtn{
  position: absolute;
  opacity: 0;
  position: absolute;
  z-index: 2;
  top: 36px;
  left: 786px;
  width: 30px;
  padding: 0;
  height: 33px;
  border: 1px solid red;
}

#tinymce_ifr{
  height:500px !important
}
</style>
